package com.sky.task;


import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Component
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 支付超时了,每一分钟处理一次
     */

    //@Scheduled(fixedDelay = 1000 * 60)
    @Scheduled(cron = "0 * * * * ?")
    public void processPayTimeOut(){
        System.out.println("处理超时订单");

        //1、根据时间差：大于15min && 状态=1
        //计算出15min前的时间
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);

        List<Orders> ordersList = orderMapper.findOrderByStatusAndTime(Orders.PENDING_PAYMENT, time);
        //遍历每一条订单，设置订单超时，取消订单，原因给出 超时自动取消
        ordersList.forEach(o->{
            o.setStatus(Orders.CANCELLED);
            o.setCancelReason("支付超时、自动取消！");
            o.setCancelTime(LocalDateTime.now());

            orderMapper.update(o);
        });





    }


    /**
     * 每天凌晨1点执行，处理派送超时的订单（检查下单2小时前的订单，如果还是仍在派送中，说明骑手可能忘记了）
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryTimeOut(){

        //找订单，1个小时前的订单。寻找派送中的订单，status=4的情况。
        System.out.println("处理派送的订单"+new Date());
        LocalDateTime time = LocalDateTime.now().minusHours(1);
        List<Orders> ordersList = orderMapper.findOrderByStatusAndTime(Orders.DELIVERY_IN_PROGRESS, time);

        if(ordersList.size()>0 && ordersList!=null){
        ordersList.forEach(o->{
            o.setStatus(Orders.COMPLETED);
            o.setDeliveryTime(LocalDateTime.now());
            orderMapper.update(o);
        });
       }
    }

}
